<template>
    <div>
        <!-- 搜索卡片  查询条件：学号、姓名、联系电话、性别、生日、家庭住址、专业班级 -->
        <el-card>
            <el-form :model="queryForm" :inline="true">
                <el-form-item label="学 号">
                    <el-input type="text" placeholder="请输入学号" v-model="queryForm.number" size="small"></el-input>
                </el-form-item>
                <el-form-item label="姓 名">
                    <el-input type="text" placeholder="请输入姓名" v-model="queryForm.username" size="small"></el-input>
                </el-form-item>
                <el-form-item label="专业班级">
                    <el-input type="text" placeholder="输入专业班级" v-model="queryForm.major" size="small"></el-input>
                </el-form-item>
                <el-form-item label="电 话">
                    <el-input type="text" placeholder="输入联系电话" v-model="queryForm.mobile" size="small"></el-input>
                </el-form-item>
                <el-form-item label="住 址">
                    <el-input type="text" placeholder="输入家庭住址" v-model="queryForm.address" size="small"></el-input>
                </el-form-item>
                <el-form-item label="性 别">
                   <el-select v-model="queryForm.sex" size="small">
                        <el-option value="男" label="男"></el-option>
                        <el-option value="女" label="女"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="生 日">
                    <el-date-picker value-format="yyyy-MM-dd" size="small" type="date" placeholder="请选择日期" v-model="queryForm.birthday"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" type="primary" @click="handleSearch">搜索</el-button>
                    <el-button size="small" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 数据卡片 -->
        <el-card class="mt12" style="margin-top: 10px">
            <div class="handel-btns">
                <div class="left-btns">
                    <el-button size="small" icon="el-icon-plus" type="primary" plain @click="handleAdd()">新增</el-button>
                    <el-button size="small" icon="el-icon-s-operation" type="success" plain @click="handleAssigned()">安排课程</el-button>
                    <el-button size="small" icon="el-icon-delete" type="danger" plain @click="handleBatchDelete()">删除</el-button>
                </div>
            </div>
            <!-- 数据表格 -->
            <el-table
                :data="studentList"
                v-loading="loading"
                border
                fit
                :header-cell-style="{background:'#f8f8f9',color:'#5a516e',padding:'10px 0px'}"
                :cell-style="{padding:'5px 0px'}"
                @selection-change="handleSelectionChange"
                style="margin: 10px 0">
                <el-table-column type="selection" align="center" width="50px"></el-table-column>
                <el-table-column label="人 脸" align="center" width="80">
                    <template slot-scope="scope">
                        <el-avatar shape="square" :size="48" cover :src="'/imgs/face/'+scope.row.face"></el-avatar>
                    </template>
                </el-table-column>
                <el-table-column label="学 号" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.number }}
                    </template>
                </el-table-column>
                <el-table-column label="姓 名" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.username }}
                    </template>
                </el-table-column>
                <el-table-column label="电 话" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.mobile }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="专业班级" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.major }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="住 址" align="center">
                    <template slot-scope="scope">
                    <span>{{ scope.row.address }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="性 别" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.sex }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="生 日" align="center">
                    <template slot-scope="scope">
                        <span>{{ formatDate(scope.row.birthday, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="启 用" align="center">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.enable" active-color="#13ce66" 
                            inactive-color="#ff4949" active-value="1" inactive-value="0"  
                            @change="changeEnable(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操 作" align="center" width="200">
                    <template slot-scope="scope">
                        <el-button size="small" type="primary" plain icon="el-icon-edit" @click="handleEdit(scope.row.id)">编辑</el-button>
                        <el-button size="small" type="danger" plain icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                :current-page="queryForm.pageNum"
                :page-size="queryForm.pageSize"
                :total="total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange">
            </el-pagination>
        </el-card>
        <!-- 新增和编辑弹窗 -->
        <el-dialog :title="title" :visible.sync="show" width="42%">
            <el-form :model="submitForm" :inline="true" label-width="120px" :rules="rules" ref="submitForm">
                <el-row>
                    <el-col :span="24" style="text-align:center;">
                        <el-form-item>
                            <el-upload
                                class="face-uploader boxCardUploadImg"
                                action="/admin-api/img/upload/face"
                                :show-file-list="false"
                                :on-success="handleFaceSuccess"
                                :headers="headers"
                                name="file"
                                :before-upload="beforeFaceUpload"
                                :on-progress="uploadFaceProcess">
                                <img v-if="'/imgs/face/'+imageUrl" :src="'/imgs/face/'+imageUrl" class="face">
                                <i v-else class="el-icon-plus face-uploader-icon"></i>
                                <i class="el-icon-edit"></i>
                            </el-upload>
                            <el-progress :style="progressStyle" :text-inside="true" :stroke-width="16" :percentage="loadProgress" :status="progressStatus"></el-progress>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="学 号" prop="number">
                            <el-input type="text" placeholder="请输入学号" v-model="submitForm.number" :readonly="title=='编辑'?true:false"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="密 码" prop="password">
                            <el-input type="password" placeholder="请输入密码" v-model="submitForm.password"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="姓 名" prop="username">
                            <el-input type="text" placeholder="请输入姓名" v-model="submitForm.username"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="专业班级" prop="major">
                            <el-input type="text" placeholder="请输入专业班级" v-model="submitForm.major"></el-input>
                        </el-form-item>
                    </el-col>
                    
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="电 话" prop="mobile">
                            <el-input type="text" placeholder="请输入联系电话" v-model="submitForm.mobile"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="住 址" prop="address">
                            <el-input type="text" placeholder="请输入家庭住址" v-model="submitForm.address"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="性 别" prop="sex">
                            <el-select v-model="submitForm.sex" placeholder="请选择">
                                <el-option v-for="(item, index) in sexList" :key="'sex-' + index" :value="item" :label="item"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="生 日" prop="birthday">
                            <el-date-picker value-format="yyyy-MM-dd" type="date" v-model="submitForm.birthday"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="dialog-footer" slot="footer" style="margin-right: 40px;">
                <el-button type="primary" @click="handleSubmit">确定</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listStudents, getStudent, addStudent, updateStudent, deleteStudent } from '@/api/student'
import { parseTime } from '@/utils/date'

export default {
    name: 'Student',
    data() {
        //检查密码是否合法
        const checkPassword = (rule,value,callback)=>{
            //要求存在内容且长度必须在6-16位
            if (this.password == null && (value.length > 16 || value.length < 6)){
                return callback(new Error('长度必须在6-16之间'))
            }
            if (this.password != value && (value.length > 16 || value.length < 6)){
                return callback(new Error('长度必须在6-16之间'))
            }
            callback()
        }
        // 检查联系电话是否合法
        const checkMobile = (rule, value, callback) => {
            if (!value) {
                return callback()
            }
            let reg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
            if (!reg.test(value)) {
                return callback(new Error('请输入合法联系电话'))
            }
            callback()
        }
        return {
            loading: true,
            submitForm: {},
            title: "新增",
            show: false,
            total: 120,
            queryForm: {
                pageNum: 1,
                pageSize: 10
            },
            sexList: ['男', '女'],
            selectList: [],
            studentList: [],
            rules: {
                number: [
                    { required: true, message: '请输入学号', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度必须在6-16之间', trigger: 'blur' }
                ],
                password:[
                    {required:true,message:'请输入密码',trigger:'blur'},
                    {validator:checkPassword,trigger:'blur'}
                ],
                username: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 16, message: '长度必须在2-16之间', trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入联系电话', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入家庭住址', trigger: 'blur' }
                ],
                major: [
                    { required: true, message: '请输入专业班级', trigger: 'blur' }
                ],
                sex: [
                    { required: true, message: '请选择性别', trigger: 'blur' }
                ],
                birthday: [
                    { required: true, message: '请选择生日', trigger: 'blur' }
                ]
            },
            fileName:null,
            password:'',
            imageUrl: 'default.jpg',
            headers: {
                Authorization: 'Bearer ' + this.$Cookie.get('login-token')
            },
            loadProgress: 0,
            progressStatus: null,
            progressStyle: "margin-top:5px;opacity: 0;"
        }
    },
    // 创建网页后查询调用数据
    created() {
        this.getList()
    },
    methods: {
        // 调用接口提交数据 - 进行添加和编辑操作的弹窗
        handleSubmit() {
            this.$refs['submitForm'].validate((valid) => {
                if (this.fileName) {
                    this.submitForm.face = this.fileName
                }
                if (valid) {
                    if (this.submitForm.id) {
                        this.submitForm.updateBy = this.$Cookie.get("username")
                        updateStudent(this.submitForm).then(res => {
                            this.show = false
                            this.getList()
                            this.submitForm = {}
                        }).catch(err => {
                            console.log(err)
                        })
                    } else {
                        this.submitForm.createBy = this.$Cookie.get("username")
                        
                        addStudent(this.submitForm).then(res => {
                            this.show = false
                            this.getList()
                            this.submitForm = {}
                        }).catch(err => {
                            console.log(err)
                        })
                    }
                }
            })
        },
        // 重置搜索
        handleReset() {
            this.queryForm = {
                pageNum: 1,
                pageSize: 10
            }
            this.getList()
        },
        // 按条件搜索
        handleSearch() {
            this.queryForm.pageNum = 1
            this.getList()
        },
        // 修改每页大小
        handleSizeChange(pageSize) {
            this.queryForm.pageSize = pageSize
            this.queryForm.pageNum = 1
            this.getList()
        },
        // 当前页修改
        handleCurrentChange(pageNum) {
            this.queryForm.pageNum = pageNum
            this.getList()
        },
        // 调用接口分页查询学生数据
        getList() {
            this.loading = true
            listStudents(this.queryForm).then(res => {
                this.studentList = res.data.records
                this.total = res.data.total
                this.loading = false
            }).catch(err => {})
            sessionStorage.removeItem("studentIds")
        },
        // 删除 - 调用接口删除记录
        handleDelete(ids) {
            this.$confirm("你确定删除id为" + ids + "的记录吗？", "提示", {
                cancelButtonText: "取消",
                confirmButtonText: "确定",
                type: "warning"
            }).then(() => {
                // 调接口删除
                deleteStudent({ ids: ids }).then(res => {
                    // 提示删除成功
                    this.$message("删除成功")
                    // 刷新列表
                    this.getList()
                }).catch(err => {
                    console.log(err)
                })
            }).catch(() => {})
        },
        // 添加 - 打开添加弹窗
        handleAdd() {
            this.show = true
            this.title = "新增"
            this.imageUrl = 'default.jpg'
            this.submitForm = { sex: '男' }
        },
        // 取消 - 关闭弹窗
        handleCancel() {
            this.show = false
        },
        // 编辑 - 打开编辑弹窗
        handleEdit(id) {
            getStudent(id).then(res => {
                // 调接口获取最新数据
                this.title = "编辑"
                this.show = true
                this.submitForm = res.data
                this.password = res.data.password
                this.imageUrl = res.data.face
            }).catch(err => {
                console.log(err)
            })
        },
        // 批量删除
        handleBatchDelete() {
            if (this.selectList) {
                let ids = this.selectList.map(o => { return o.id })
                console.log('ids---------->', ids)
                this.handleDelete(ids)
            }
        },
        // 多选
        handleSelectionChange(val) {
            this.selectList = val
        },
        handleAssigned(){
            if (this.selectList) {
                let ids = this.selectList.map(o => o.id)
                sessionStorage.setItem("studentIds",JSON.stringify(ids))
                this.$router.push('/info/course')
            }
        },
        // 时间格式化
        formatDate(value, format) {
            return parseTime(new Date(value), format)
        },
         // 头像上传前调用函数
        beforeFaceUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        // 上传头像进度
        uploadFaceProcess(event, file, fileList) {
            this.progressStyle = "margin-top:5px;opacity: 1;",
            this.loadProgress = parseInt(event.percent);
            if (this.loadProgress >= 100) {
                this.progressStatus = "success"
                this.loadProgress = 100
                setTimeout(() => { this.progressStyle = "margin-top:5px;opacity: 0;"; this.progressStatus = null }, 1000)
            }
        },
        // 头像上传成功调用函数
        handleFaceSuccess(res, file) {
            this.fileName = res.data
            this.imageUrl = this.fileName;
        },
        //修改启用状态
        changeEnable(data){
            data.updateBy = this.$Cookie.get("username")
            updateStudent(data).catch(err=>{console.log(err)})
        }
    }
}
</script>

<style scoped>
.el-form-item {
    margin: 10px;
}
.face-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 20px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.fa ce-uploader .el-upload:hover {
    border-color: #409EFF;
}
.face-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.face {
    width: 178px;
    height: 178px;
    border-radius: 20px;
    display: block;
}
.boxCardUploadImg {
    width: 178px;
    height: 178px;
    border-radius: 20px;
    position: relative;
}
.boxCardUploadImg:hover {
    cursor: pointer;
}
.boxCardUploadImg:hover::after {
    content: '';
    background-color: rgba(0, 0, 0, 0.3);
    position: absolute;
    left: 0;
    height: 100%;
    top: 0px;
    width: 100%;
    z-index: 99;
    border-radius: 20px;
}
.boxCardUploadImg i {
    display: none;
}
.boxCardUploadImg:hover i {
    position: absolute;
    font-size: 48px;
    display: initial;
    z-index: 999;
    color: #fff;
    top: 65px;
    left: 65px;
}
</style>